<template>
  <el-dialog ref="drawer" :title="title" :visible.sync="drawer" close-on-press-escape destroy-on-close
    @close="resetForm('ruleForm')">
    <div class="draw-body" style="padding: 0 50px">
      <el-form v-if="drawer" ref="ruleForm" :model="object" :rules="rules" label-width="120px" class="demo-ruleForm"
        label-suffix=":">
        <el-row>
          <el-col v-if="type !== 'edit'" :span="24">
            <el-form-item label="用户类型">
              <el-radio-group v-model="userType">
                <el-radio :label="1">正式工</el-radio>
                <el-radio :label="0">临时工</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <template v-if="userType">
            <el-col :span="24">
              <el-form-item label="正式工" prop="userId">
                <el-select v-model="object.userId" placeholder="请选择">
                  <el-option v-for="item in personalList" :key="item.id" :label="item.userInfo.username"
                    :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="是否为负责人">
                <el-radio-group v-model="object.isLeader">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- <template v-if="object.isLeader">
              <el-col :span="24">
                <el-form-item label="登陆账号" prop="account">
                  <el-input
                    v-model="object.account"
                    maxlength="20"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </template> -->
          </template>
          <template v-else>
            <el-col :span="24">
              <el-form-item label="头像" prop="picture">
                <div class="uplodeBox">
                  <el-upload class="avatar-uploader" name="multipartfiles"
                    accept="image/png, image/jpeg,image/jpg,image/gif"
                    action="/api/v1/welder-fms-second/upload/fileUpload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="object.picture" :src="object.picture | imgPath" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="真实姓名" prop="username">
                <el-input v-model="object.username" maxlength="10" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="年龄" prop="age">
                <el-input-number v-model="object.age" :precision="0" :controls="false" :min="0" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="object.sex">
                  <el-radio :label="2">男</el-radio>
                  <el-radio :label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="object.phone" maxlength="11" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属企业" prop="entName">
                <el-input v-model="object.entName" maxlength="20" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="人员编号" prop="serialNum">
                <el-input v-model="object.serialNum" maxlength="20" show-word-limit />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="简介" prop="remark">
                <el-input v-model="object.remark" type="textarea" maxlength="30" show-word-limit />
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button @click="drawer = false">取消</el-button>
      <el-button type="primary" @click.native="submitForm('ruleForm')">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    postHandle
  } from '@/api'
  import {
    validPhone
  } from '@/utils/validate'
  import {
    getEntSpaceId,
    getSpaceId
  } from '@/utils/auth'
  export default {
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!validPhone(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      }
      return {
        drawer: false,
        title: '',
        userType: 1,
        id: null,
        object: {
          userId: null,
          isLeader: 0,
          account: null,
          picture: null,
          username: null,
          age: null,
          sex: null,
          phone: null,
          entName: null,
          serialNum: null,
          remark: null
        },
        rules: {
          userId: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }],
          account: [{
            required: true,
            message: '请输入账号',
            trigger: 'change'
          }],
          username: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          phone: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
            {
              validator: validatePhone
            }
          ],
          serialNum: [{
            required: true,
            message: '请输入编号',
            trigger: 'blur'
          }]
        },

        personalList: [],
        persnoalPage: {
          p: 1,
          ps: 9999
        }
      }
    },
    watch: {
      userType: {
        handler(v) {
          if (v) this.getPerson()
        },
        immediate: true
      }
    },
    methods: {
      open(type, id) {
        this.type = type
        this.title = this.type === 'add' ? '新增' : '修改'
        if (this.type === 'edit') {
          this.userType = 0
          this.id = id
          this.getUserInfoById()
        }
       
        this.getPerson()
        this.drawer = true
      },

      handleAvatarSuccess(res, file) {
        this.object.picture = res.result[0]
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 100
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 10MB!')
        }
        return isLt2M
      },

      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.type === 'add') {
              if (this.userType) {
                this.addFormalWorker()
              } else {
                this.addTemporaryWorker()
              }
            } else {
              this.editTemporaryWorker()
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 添加正式工
      addFormalWorker() {
        postHandle('/api/v1/welder-sbtx-second/space-comb/add-user', {
            obj: {
              userId: this.object.userId,
              account: this.object.account,
              isLeader: this.object.isLeader,
              spaceId: getSpaceId()
            }
          })
          .then((response) => {
            this.$emit('getList')
            this.drawer = false
          })
          .catch((error) => {
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(key + '.' + data[key]))
            }
          })
      },

      // 添加临时工
      addTemporaryWorker() {
        postHandle(
            '/api/v1/welder-sbtx-second/space-comb/create-member', {
              obj: {
                spaceId: getSpaceId(),
                userInfo: this.object
              }
            }
          )
          .then((response) => {
            this.$emit('getList')
            this.drawer = false
          })
          .catch((error) => {
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(key + '.' + data[key]))
            }
          })
      },

      // 修改临时工
      editTemporaryWorker() {
        postHandle(
            '/api/v1/welder-uac-second/user-information-comb/update-user-info/' + this.id, {
              obj: this.object
            }
          )
          .then((response) => {
            this.$emit('getList')
            this.drawer = false
          })
          .catch((error) => {
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(key + '.' + data[key]))
            }
          })
      },

      getUserInfoById() {
        postHandle(`/api/v1/welder-uac-second/user-information/show/${this.id}`, {})
          .then((response) => {
            this.object = {
              account: response.result.account,
              picture: response.result.picture,
              username: response.result.username,
              age: response.result.age,
              sex: response.result.sex,
              phone: response.result.phone,
              entName: response.result.entName,
              serialNum: response.result.serialNum,
              remark: response.result.remark
            }
          })
          .catch((error) => {
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(key + '.' + data[key]))
            }
          })
      },

      resetForm(formName) {
        this.$refs[formName].resetFields()
      },

      getPerson() {
        const req = {
          d: {
            filters: [{
              field: 'spaceId',
              operator: 'EQUALS',
              value: getEntSpaceId()
            },{
              field: 'spaceId',
              operator: 'EQUALS',
              value: getEntSpaceId()
            }
          ],
            page: this.persnoalPage,
            retPage: true
          },
          obj: {
            flag: true
          }
        }
        postHandle(
          '/api/v1/welder-sbtx-second/space-user-member-comb/get-list',
          req
        ).then((response) => {
          this.personalList = response.result
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>